<?php
namespace app\model;


class Theme {
	static function getById($id) {
	    if (empty($id)) {
			return false;
		}
		$sql = "SELECT * FROM " . tablename(t_theme) . " where id = :id and status <> '-1'";
		$row = db_find($sql, array(":id"=>$id));
		return $row;
	}


    static function getshareinfo($theme,$config,$fans,$shopname,$workername,$recordid=0,$fromuid=0){
        
        $themeid= $theme['id'];
        $themyrecord = Record::getLastGroupByOpenId($fans['openid'],$themeid);
        $myworker = Worker::getThemeWorkerByOpenid($fans['openid'],$themeid,1);
        //分享jssdk
        if($themyrecord['status'] >= 1 && !empty($themyrecord)){
            if (!empty($config['sharetitlexcx2']) && empty($myworker)){
                $sharetitlexcx = $config['sharetitlexcx2'];
            }else{
                $sharetitlexcx = $theme['title'];
            }
            $sharetitle = str_replace("NICK",$fans['nickname'],$sharetitlexcx);
            $sharetitle = str_replace("NAME",$themyrecord['username'],$sharetitle);
            $sharetitle = str_replace("SHOPNAME",$shopname,$sharetitle);

            if ($themyrecord['type']==1){
                $recordid = $themyrecord['pid'];
            }else{
                $recordid = $themyrecord['id'];
            }
        }else{
            if (!empty($config['sharetitlexcx']) && empty($myworker)){
                $sharetitlexcx = $config['sharetitlexcx'];
            }else{
                $sharetitlexcx = $theme['title'];
            }
            $sharetitle = str_replace("NICK",$fans['nickname'],$sharetitlexcx);
            $sharetitle = str_replace("SHOPNAME",$shopname,$sharetitle);
        }

        if (!empty($myworker)) {
            $recordid = 0;
        }
        if ($config['iswxshare']==1) {
            $theme['title'] = $sharetitle;
        }
        if ( $config['livedata']['yure']==1 && in_array($config['livedata']['livestatus'], array(101,102,105,106))) {
            if(!empty($config['livedata']['lname'])){
                $sharetitle=$config['livedata']['lname'];
            }
        }
        if (!empty($workername) && $config['isshowkefu']==1){
            $sharetitle = $sharetitle ."【客服:".$workername."】";
        }

        // $sharedesc = $theme['desc'];
        if (empty($config['shareimgxcx'])){
            $shareimgurl = tomedia($config['headlogo']);
        }else{
            $shareimgurl = tomedia($config['shareimgxcx']);
        }

        // $theme['title'] = Theme::encode($theme['title'],'&#',';');
        if (!empty($fans['uid'])) {
            $fromuid = $fans['uid'];
        }
        $sharedata = array(
            'fromuid'=>$fromuid,
            'recordid'=>$recordid,
            'themeid'=>$themeid,
        );
        if ($system['friend']==1 || $config['isicon']==3) {
            if (empty($themyrecord)){
                $sharedata['help_uid'] = $help_uid; 
            }
        }
        $shareurl =   Theme::createwxAppUrl('index',$sharedata);

        $shareinfo['sharetitle'] = $sharetitle;
        $shareinfo['shareimgurl'] = $shareimgurl;
        $shareinfo['shareurl'] = $shareurl;
        return $shareinfo;
    }
    static function createwxAppUrl($do, $query = array()){
        global $_G, $_P;
        if ($do=='dopay'){
            $url = $this->createMobileUrl($do, $query);
        }else{
            $str ='';
            foreach ($query as $key => $value) {
                // if ($key <> 'themeid' && $key <> 'fromuid' &&  $key <> 'a'){
                    $str .= "&" . $key ."=" . $value;
                // }
            }

            $str = str_replace("?&", "?", $str);
            //rewrite ^/(.*)/(.*)/(.*)/(.*)/(.*).aspx?(.*)$ /app/index.php?c=entry&m=$1&i=$2&themeid=$3&fromuid=$4&do=$5&$6 break;
            //rewrite ^/(.*)/(.*)/(.*)/(.*)/(.*).aspx?(.*)$ /app/index.php?$6&c=entry&m=$1&i=$2&themeid=$3&fromuid=$4&do=$5 break;

            if (empty($query['themeid'])){
                $query['themeid']=0;
            }
            if (empty($query['fromuid'])){
                $query['fromuid']=intval($_G['member']['uid']);
            }
            $url = "pages/" . $do . "/" . $do ."?softname=" . MODULE_NAME . $str;

            //$url = $this->createMobileUrl($do, $query);
            if (!empty($query['themeid'])) {
                $item = Theme::getById($query['themeid']);
                if(!empty($item['softkey'])) {
                    $url = $url . "&softkey=" . $item['softkey'];
                }
            }
        }
        return $url;
    }

    static function getByTitle($title) {
        if (empty($title)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_theme) . " where title = :title limit 1";
        $row = db_find($sql, array(":title"=>$title));
        return $row;
    }
    static function getAllTheme() {
        $sql = "SELECT * FROM " . tablename(t_theme) . " 
                        where status=1 ORDER BY id,status desc";
        $row = db_select($sql);
        return $row;
    }

    static function getDefaultTheme($uniacid) {
        if (empty($uniacid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_shop) . " 
                        where status <> '-1' ORDER BY indexno,id,status desc limit 1";
        $row = db_select($sql);
        return $row;
    }

    static function getDefaultThemenew() {
        $sql = "SELECT * FROM " . tablename(t_theme) . " 
                        where status <> '-1' ORDER BY id desc limit 1";
        $row = db_find($sql);
        return $row['id'];
    }

    static function getThemeByIdxcx($themeid){
        global $_P;
        $theme = self::getById($themeid);        
        if(!empty($theme['softkey'])) {
            if ($theme['softkey']!==$_P['softkey']) {
                $theme = false;
            }
        }
        return $theme;
    }

    static function getThemeById($themeid){
        // $cachekey = 'theme'.$_G['mpid'].MODULE_NAME.'-'.$themeid;
        // $theme = cache_load($cachekey);
        // if(empty($theme)){
            $theme = self::getById($themeid);
        //     if(!empty($theme)){
        //         cache_write($cachekey, $theme);
        //     }
        // }
        return $theme;
    }

    static function clearTheme($themeid){
        global $_G;
     //    $cachekey = 'theme'.$_G['mpid'].MODULE_NAME.'-'.$themeid;
	    // cache_delete($cachekey);
     //    $cachekey = 'setting'.$_G['mpid'].MODULE_NAME.$themeid;
     //    cache_delete($cachekey);
    }

    static function getConfigByUniacidAndKey($uniacid,$key) {
        global $_G;
        // $cachekey = 'setting'.$uniacid.MODULE_NAME.$key;
        // $settings = cache_load($cachekey);
        // if(empty($settings)){
            $settings = db_get(t_config, array('`key`' => $key, 'uniacid' =>$uniacid), array('value'));
            if (is_array($settings)) {
                $settings = xunserializer($settings['value']);
        //         cache_write($cachekey, $settings);
            } else {
                $settings = array();
            }
        // }
        return $settings;
    }

    static function getConfig($key) {
        global $_G;
        // $cachekey = 'setting'.$_G['mpid'].MODULE_NAME.$key;
        // $settings = cache_load($cachekey);
        // if(empty($settings)){
            $settings = db_get(t_config, array('`key`' => $key), array('value'));
            if (is_array($settings)) {
                $settings = xunserializer($settings['value']);
        //         cache_write($cachekey, $settings);
            } else {
                $settings = array();
            }
        // }
        return $settings;
    }


    static function setConfig($data,$key,$accountid) {
        global $_G;
        if (empty($key)) {
            return FALSE;
        }
        $record = array();
        $record['value'] = serialize($data);
        $exists = db_getcolumn(t_config, array('`key`' => $key), 'id');
        if ($exists) {
            if ($_G['isSuperAdmin']){
                $record['uniacid'] = $accountid;
            }
            $return = db_update(t_config, $record, array('`key`' => $key));
        } else {
            $record['key'] = $key;
            if ($_G['isSuperAdmin']){
                $record['uniacid'] = $accountid;
            }else{
                $record['uniacid'] = $_G['mpid'];
            }
            $return = $insertid = db_insert(t_config, $record);
        }
        // if ($_G['isSuperAdmin']){
        //     $cachekey = 'setting'.$accountid.MODULE_NAME.$key;
        // }else{
        //     $cachekey = 'setting'.$_G['mpid'].MODULE_NAME.$key;
        // }
        
        // cache_write($cachekey, $data);
        return $return;
    }

    static function getByUserId($userid) {
        if (empty($userid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_theme) . " where webuid = :uid order by id desc limit 1";
        $row = db_find($sql, array(":uid"=>$userid));
        return $row;
    }


	static function getTotal($condition){
	    if(empty($condition)){
            return false;
        }
        $total = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_theme ) . "as s
			WHERE  {$condition} ORDER BY s.indexno" );
        return $total;
    }


    static function getListByCity($province,$city,$uniacid){
        if(empty($city) || empty($uniacid) || empty($province)){
            return false;
        }
        $sql = "SELECT s.*,s.id as shopid  FROM " . tablename ( t_theme ) . " as s 
						WHERE s.uniacid = :uniacid and s.province =:province and s.city = :city and s.status = 1 ORDER BY s.indexno,s.status desc";
        $list = db_select($sql,array(":province"=>$province,":city"=>$city,":uniacid"=>$uniacid));
        return $list;
    }

    static function getListByProvince($province,$uniacid){
        if(empty($province) || empty($uniacid)){
            return false;
        }
        $sql = "SELECT s.*,s.id as shopid  FROM " . tablename ( t_theme ) . " as s 
						WHERE s.uniacid = :uniacid and s.province = :province and s.status = 1  ORDER BY s.indexno,s.status desc";
        $list = db_select($sql,array(":province"=>$province,":uniacid"=>$uniacid));
        return $list;
    }

    static function getListLimit($uniacid,$limit = 100){

        $sql = "SELECT s.* FROM " . tablename ( t_theme ) . " as s 
						WHERE   s.uniacid = '{$uniacid}' and s.status = 1 ORDER BY s.indexno LIMIT " .$limit ;
        $list = db_select($sql);
        return $list;
    }

    static function getDoingList($uniacid){
        if(empty($uniacid)){
            return false;
        }
        $sql = "SELECT s.* FROM " . tablename ( t_theme ) . " as s 
						WHERE  uniacid =  {$uniacid} and status = 1 ORDER BY s.indexno,s.id desc,s.status desc";
        $list = db_select($sql);
        return $list;
    }

    static function getList($condition,$pageNumber,$pageSize=10){
        if(empty($condition)){
            return false;
        }
        $sql = "SELECT s.* FROM " . tablename ( t_theme ) . " as s 
						WHERE   {$condition} ORDER BY s.indexno,s.id desc,s.status desc
							 LIMIT " . ($pageNumber - 1) * $pageSize . ","  . $pageSize;
        $list = db_select($sql);
        return $list;
    }


	static function delete($id) {
	    if (empty($id)) {
	        return false;
	    }
	    db_delete (t_theme, array('id'=>$id));
        db_delete (t_config, array('key'=>$id));
        self::clearTheme($id);
	    return true;
	}

    static function update($id,$data) {
        if (empty($id)) {
            return false;
        }
        db_update (t_theme,$data, array('id'=>$id));
        self::clearTheme($id);
        return true;
    }

	static function setStatusById($id,$status = 0) {
	    if (empty($id)) {
	        return false;
	    }
	    db_update (t_theme,array('status' =>$status), array('id'=>$id));
	    return true;
	}



  /**
   * 将ascii码转为字符串
   * @param type $str 要解码的字符串
   * @param type $prefix 前缀，默认:&#
   * @return type
   */
  static function decode($str, $prefix="l") {
    $str = str_replace($prefix, "", $str);
    $a = explode("O", $str);
    foreach ($a as $dec) {
      if ($dec < 128) {
        $utf .= chr($dec);
      } else if ($dec < 2048) {
        $utf .= chr(192 + (($dec - ($dec % 64)) / 64));
        $utf .= chr(128 + ($dec % 64));
      } else {
        $utf .= chr(224 + (($dec - ($dec % 4096)) / 4096));
        $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
        $utf .= chr(128 + ($dec % 64));
      }
    }
    return $utf;
  }
  /**
   * 将字符串转换为ascii码
   * @param type $c 要编码的字符串
   * @param type $prefix 前缀，默认：&#
   * @return string
   */
  static function encode($c, $prefix="l", $rigfix="O") {
    $len = strlen($c);
    $a = 0;
    while ($a < $len) {
      $ud = 0;
      if (ord($c{$a}) >= 0 && ord($c{$a}) <= 127) {
        $ud = ord($c{$a});
        $a += 1;
      } else if (ord($c{$a}) >= 192 && ord($c{$a}) <= 223) {
        $ud = (ord($c{$a}) - 192) * 64 + (ord($c{$a + 1}) - 128);
        $a += 2;
      } else if (ord($c{$a}) >= 224 && ord($c{$a}) <= 239) {
        $ud = (ord($c{$a}) - 224) * 4096 + (ord($c{$a + 1}) - 128) * 64 + (ord($c{$a + 2}) - 128);
        $a += 3;
      } else if (ord($c{$a}) >= 240 && ord($c{$a}) <= 247) {
        $ud = (ord($c{$a}) - 240) * 262144 + (ord($c{$a + 1}) - 128) * 4096 + (ord($c{$a + 2}) - 128) * 64 + (ord($c{$a + 3}) - 128);
        $a += 4;
      } else if (ord($c{$a}) >= 248 && ord($c{$a}) <= 251) {
        $ud = (ord($c{$a}) - 248) * 16777216 + (ord($c{$a + 1}) - 128) * 262144 + (ord($c{$a + 2}) - 128) * 4096 + (ord($c{$a + 3}) - 128) * 64 + (ord($c{$a + 4}) - 128);
        $a += 5;
      } else if (ord($c{$a}) >= 252 && ord($c{$a}) <= 253) {
        $ud = (ord($c{$a}) - 252) * 1073741824 + (ord($c{$a + 1}) - 128) * 16777216 + (ord($c{$a + 2}) - 128) * 262144 + (ord($c{$a + 3}) - 128) * 4096 + (ord($c{$a + 4}) - 128) * 64 + (ord($c{$a + 5}) - 128);
        $a += 6;
      } else if (ord($c{$a}) >= 254 && ord($c{$a}) <= 255) { //error
        $ud = false;
      }
      $scill .= $prefix.$ud.$rigfix;
    }
    if ($prefix!="&#") {
        $scill = str_replace('3', 'a', $scill);
        $scill = str_replace('1', 'x', $scill);
    }
    return $scill;
  }


    //  ($config['formtextpay'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
    static function ButtonTextReplaceXCX($text,$joinfee,$primeprice,$groupprice) {
        $text = str_replace("#fee",$joinfee,$text);
        $text = str_replace("#dan",$primeprice,$text);
        $text = str_replace("#tuan",$groupprice,$text);
        //如果有#br
        // if (strstr($text,"#br")!==false ){
        //     $text = "<view class=\"h2\">" . str_replace("#br","</view><view class=\"bmf\">",$text) . "</view>";
        // }else{
        //     $text = "<view class=\"bmf\">" . $text . "</view>";
        // }
        return $text;
    }
    
    static function ButtonTextReplacefc($text,$joinfee,$primeprice,$groupprice) {
        $text = str_replace("#fee",$joinfee,$text);
        $text = str_replace("#dan",$primeprice,$text);
        $text = str_replace("#tuan",$groupprice,$text);
        //如果有#br
        if (strstr($text,"#br")!==false ){
            $text = "<h2>" . str_replace("#br","</h2><p>",$text) . "</p>";
        }else{
            $text = "<p>" . $text . "</p>";
        }
        return $text;
    }
    

    static function ButtonTextReplace($text,$joinfee,$primeprice,$groupprice) {
        $text = str_replace("#fee",$joinfee,$text);
        $text = str_replace("#dan",$primeprice,$text);
        $text = str_replace("#tuan",$groupprice,$text);
        if($_G['companyname'] =='飞驰软件'){
            //如果有#br
            if (strstr($text,"#br")!==false ){
                $text = "<p>" . str_replace("#br","</p><span>",$text) . "</span>";
            }else{
                $text = "<span>" . $text . "</span>";
            }
        }else{
            $text = str_replace("￥","<i>￥</i>",$text);
            $text = str_replace(".00","<i>.00</i>",$text);
            $text = str_replace("#br","<br>",$text);
            $text = str_replace("￥","<em>￥</em>",$text);
            $text = str_replace(".00","<em>.00</em>",$text);
        }
        return $text;
    }
    
    static function ButtonTextYx2020($text,$joinfee,$primeprice,$groupprice) {
        $text = str_replace("#fee",$joinfee,$text);
        $text = str_replace("#dan",$primeprice,$text);
        $text = str_replace("#tuan",$groupprice,$text);
        if($_G['companyname'] =='飞驰软件'){
            //如果有#br
            if (strstr($text,"#br")!==false ){
                $text = "<p>" . str_replace("#br","</p><span>",$text) . "</span>";
            }else{
                $text = "<span>" . $text . "</span>";
            }
        }else{
            if (strstr($text,"#br")!==false ){
                $text = "<h2>" . str_replace("#br","</h2><p>",$text) . "</p>";
            }else{
                $text = "<p>" . $text . "</p>";
            }
            // $text = str_replace("￥","<i>￥</i>",$text);
            // $text = str_replace(".00","<i>.00</i>",$text);
            // $text = str_replace("#br","<br>",$text);
            // $text = str_replace("￥","<em>￥</em>",$text);
            // $text = str_replace(".00","<em>.00</em>",$text);
        }
        return $text;
    }

    static function ButtonTextReplaceEncode($text,$joinfee,$primeprice,$groupprice) {
        return Theme::encode(Theme::ButtonTextReplace($text,$joinfee,$primeprice,$groupprice));
    }


    static function workerreport($themeid,$workerid,$data){
        global $_G;
        if (empty($workerid)){
            return false;
        }

        $workerreport = db_find("SELECT * FROM ".tablename(t_workerreport)."
            WHERE themeid = ".$themeid." and workerid = " . $workerid ." and riqi ='" . date("Y-m-d") ."'");
        if (empty($workerreport)) {
            $data['uniacid'] = $_G['mpid'] ;
            $data['themeid'] = $themeid ;
            $data['workerid'] = $workerid ;
            $data['riqi'] = date("Y-m-d") ;
            $data['renewtime'] = TIMESTAMP ;
            $insertid = db_insert(t_workerreport,$data);
        }else{


            if (!empty($data['scansum'])){
                $keyname = 'scansum';
                $keyvalue = $data['scansum'];
            }elseif (!empty($data['forward'])){
                $keyname = 'forward';
                $keyvalue = $data['forward'];
            }elseif (!empty($data['newfans'])){
                $keyname = 'newfans';
                $keyvalue = $data['newfans'];
            }elseif (!empty($data['record'])){
                $keyname = 'record';
                $keyvalue = $data['record'];
            }elseif (!empty($data['recordzx'])){
                $keyname = 'recordzx';
                $keyvalue = $data['recordzx'];
            }elseif (!empty($data['fee'])){
                $keyname = 'fee';
                $keyvalue = $data['fee'];
            }elseif (!empty($data['comm'])){
                $keyname = 'comm';
                $keyvalue = $data['comm'];
            }elseif (!empty($data['refundfee'])){
                $keyname = 'refundfee';
                $keyvalue = $data['refundfee'];
            }elseif (!empty($data['refund'])){
                $keyname = 'refund';
                $keyvalue = $data['refund'];
            }elseif (!empty($data['recordxx'])){
                $keyname = 'recordxx';
                $keyvalue = $data['recordxx'];
            }


            db_query("UPDATE ".tablename(t_workerreport)." SET " . $keyname. " = " . $keyname. " + " . $keyvalue . " WHERE themeid = ".$themeid." and workerid = " . $workerid ." and riqi ='" . date("Y-m-d") ."'");
        }

    }

    static function renewreport($themeid){
        global $_G;
        $theme = Theme::getThemeById($themeid);
        $todaytime = $theme['begintime'] ;
        
        if($theme['endtime'] > $theme['begintime']+60*60*24){
        while ($todaytime<TIMESTAMP && $todaytime <$theme['endtime'] ) {
            $today = date('Y-m-d',$todaytime);
            $daylist = db_find("SELECT * FROM " . tablename ( t_report ) . " WHERE software = '".MODULE_NAME."' and  themeid = '{$themeid}' and riqi = '" .$today ."'");
            $isrenew = false;
            if (empty($daylist)){
                $isrenew = true;
            }else{
                if ($daylist['renewtime'] < strtotime($daylist['riqi']." 23:59:59")) {
                    $isrenew = true;
                }
            }
            if ($isrenew == true){
                $begintime  = strtotime(date('Y-m-d 00:00:00',$todaytime));
                $endtime = strtotime(date('Y-m-d 23:59:59',$todaytime));

                if ($theme['refundfee']>0){
                    $returnrecord =" or status = -1";
                    $returnorder =" or paystate = -1";
                    $todayreturn = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and status = -1 and refundtime >= {$begintime} and refundtime <= {$endtime}");
                    $todayreturnfee = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
                        WHERE  themeid = '{$themeid}' and paystate = -1 and realfee > 0 and refundtime >= {$begintime} and refundtime <= {$endtime}" );
                }

                $todaynewfans = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . "
                        WHERE  themeid = '{$themeid}' and addtime >= {$begintime} and addtime <= {$endtime}");

                $todayrecord = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE themeid = '{$themeid}' and (status > 0  and status!=3 {$returnrecord}) and addtime >= {$begintime} and addtime <= {$endtime}");


                $todayrecordxx = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and status=3 and addtime >= {$begintime} and addtime <= {$endtime}");

                $todayfee = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
                        WHERE  themeid = '{$themeid}' and (paystate = 1 {$returnorder}) and realfee > 0 and paytime >= {$begintime} and paytime <= {$endtime}" );

                $todaycomm = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
                    WHERE  themeid ='{$themeid}'  and status  = 1 and addtime >= {$begintime} and addtime <= {$endtime}" );
                $data = array(
                    'software' => MODULE_NAME,
                    'uniacid' => $_G['mpid'] , 
                    'themeid' => $themeid , 
                    'riqi' => $today , 
                    'renewtime' => TIMESTAMP , 
                    'newfans' => $todaynewfans , 
                    'record' => $todayrecord , 
                    'recordxx' => $todayrecordxx , 
                    'fee' => $todayfee , 
                    'comm' => $todaycomm ,                  
                ); 
                
                if ($theme['refundfee']>0){
                    $data['refund'] = $todayreturn;
                    $data['refundfee'] =  $todayreturnfee;
                }

                if (empty($daylist)) {
                    $insertid = db_insert(t_report,$data);
                }else{
                    db_update(t_report, $data, array('id' => $daylist['id']));
                }
            }
            $todaytime = $todaytime + 60*60*24;
        }
        }
        $result = db_select("SELECT * FROM " . tablename ( t_report ) . " WHERE software = '".MODULE_NAME."' and themeid = '{$themeid}' and riqi<='" . date('Y-m-d') ."' order by riqi desc");
        return $result;
    }

    static function renewworkreport($themeid,$workerid){
        global $_G;
        $theme = Theme::getThemeById($themeid);
        $config =   Theme::getConfig($themeid);
        $todaytime = $theme['begintime'] ;
        $jishu = 0 ;

        $gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
            WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" ));
        if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $gsum12==0){
            $freerecord = true;
        }else{
            $freerecord = false;
        }

        //db_query("truncate table" . tablename ( t_workerreport ));
        if($theme['endtime'] > $theme['begintime']+60*60*24){
        while ($todaytime<TIMESTAMP && $todaytime <$theme['endtime'] ) {
            $today = date('Y-m-d',$todaytime);
            $begintime  = strtotime(date('Y-m-d 00:00:00',$todaytime));
            $endtime = strtotime(date('Y-m-d 23:59:59',$todaytime));
            if (!empty($workerid)){
                $tiaojian = " and uid = " . $workerid;
            }
            $workerlist = db_select('SELECT * FROM ' . tablename(t_worker) . ' WHERE status=1 and themeid = '.$themeid.$tiaojian.' ORDER BY uid');
            foreach ($workerlist as $index => $item) {
                if ($theme['refundfee']>0){
                    $returnrecord =" or status = -1";
                    $returnorder =" or paystate = -1";
                    $todayreturn = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and workerid = '{$item['uid']}' and status = -1 and refundtime >= {$begintime} and refundtime <= {$endtime}");
                    
                    $todayreturnfee = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and workerid = '{$item['uid']}' and status = -1 and refundtime >= {$begintime} and refundtime <= {$endtime}");
                    // $todayreturnfee = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
                    //     WHERE uniacid = '{$_G['mpid']}' and themeid = '{$themeid}' and workerid = '{$item['uid']}' and paystate = -1 and realfee > 0 and refundtime >= {$begintime} and refundtime <= {$endtime}" );
                }
                if ($freerecord){
                    $returnrecord =" or status = 0";
                }

                $todaynewfans = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . "
                        WHERE  themeid = '{$themeid}' and workerid = '{$item['uid']}'  and addtime >= {$begintime} and addtime <= {$endtime}");

                $todayrecord = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and workerid = '{$item['uid']}'  and (status > 0  and status!=3 {$returnrecord}) and addtime >= {$begintime} and addtime <= {$endtime}");

                $todayrecordzx = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and fromuid = '{$item['uid']}' and workerid = '{$item['uid']}' and (status > 0  and status!=3 {$returnrecord}) and addtime >= {$begintime} and addtime <= {$endtime}");

                $todayrecordxx = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and workerid = '{$item['uid']}'  and status=3 and addtime >= {$begintime} and addtime <= {$endtime}");

                $sql = 'SELECT sum(fee) FROM ' . tablename ( t_record ) . "
                        WHERE  themeid = '{$themeid}' and workerid = '{$item['uid']}'  and (status > 0  and status!=3 {$returnrecord}) and addtime >= {$begintime} and addtime <= {$endtime}";
                $todayfee = db_fetchcolumn ( $sql );

                $todaycomm = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
                    WHERE  themeid ='{$themeid}' and uid = '{$item['uid']}'   and status  = 1 and addtime >= {$begintime} and addtime <= {$endtime}" );

                $data = array(
                    'uniacid' => $_G['mpid'] , 
                    'themeid' => $themeid , 
                    'workerid' => $item['uid'] , 
                    'riqi' => $today , 
                    'renewtime' => TIMESTAMP , 
                    'newfans' => $todaynewfans , 
                    'record' => $todayrecord , 
                    'recordzx' => $todayrecordzx , 
                    'recordxx' => $todayrecordxx , 
                    'fee' => $todayfee , 
                    'comm' => $todaycomm ,                  
                ); 
                
                if ($theme['refundfee']>0){
                    $data['refund'] = $todayreturn;
                    $data['refundfee'] =  $todayreturnfee;
                }

                $daylist = db_find("SELECT * FROM " . tablename ( t_workerreport ) . " WHERE themeid = '{$themeid}' and workerid = '{$item['uid']}' and riqi = '" .$today ."'");

                if (empty($daylist)) {
                    $insertid = db_insert(t_workerreport,$data);
                }else{
                    db_update(t_workerreport, $data, array( 'id' => $daylist['id']));
                }
                $jishu = $jishu+1;
            }

            $todaytime = $todaytime + 60*60*24;
        }
        }
        //$result = db_select("SELECT * FROM " . tablename ( t_workerreport ) . " WHERE software = '".MODULE_NAME."' and uniacid = '{$_G['mpid']}' and themeid = '{$themeid}' and riqi<='" . date('Y-m-d') ."' order by riqi desc");
        return $jishu;
    }
}
?>